#include "widget.h"
#include "ui_widget.h"
#include <QDebug>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    seconds = 0;
    timer = new QTimer(this);
	player = new QMediaPlayer(this);
    ui->setupUi(this);

    connect(timer, SIGNAL(timeout()), this, SLOT(flushTime()));
}

Widget::~Widget()
{
    delete ui;
}

void Widget::on_pushButton_clicked()
{
    QString text = ui->pushButton->text();
    if (text == "start")
    {
        seconds = ui->spinBox->text().toInt() * 60;
        startTime = QTime::currentTime();

		ui->pushButton->setText("stop");
		player->stop();
		hide();
        startTime.start();
        timer->start(100);
    }
    else
    {
        timer->stop();
        ui->lcdNumber->display(0);
        ui->pushButton->setText("start");
    }
}

void Widget::flushTime()
{
    auto durtion = startTime.elapsed();
    if (durtion >= seconds * 1000)
    {
        timer->stop();
        ui->lcdNumber->display(0);
		ui->pushButton->setText("start");
		player->setMedia(QUrl::fromLocalFile("I:/Desktop/WaveTest/Kalimba.mp3"));
		player->play();
        showNormal();
    }
    else
    {
        int time = static_cast<int>(seconds * 1000 - durtion);
        QString text = formatTime(time);
        ui->lcdNumber->display(text);
    }
}

QString Widget::formatTime(int ms)
{
    int ss = 1000;
    int mi = ss * 60;
    int hh = mi * 60;
    int dd = hh * 24;

    long day = ms / dd;
    long hour = (ms - day * dd) / hh;
    long minute = (ms - day * dd - hour * hh) / mi;
    long second = (ms - day * dd - hour * hh - minute * mi) / ss;
    long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;

    QString hou = QString::number(hour,10);
    QString min = QString::number(minute,10);
    QString sec = QString::number(second,10);
    QString msec = QString::number(milliSecond,10);

    //qDebug() << "minute:" << min << "second" << sec << "ms" << msec <<endl;

    return min + ":" + sec ;
}
